<?php
/**
 * Created by PhpStorm.
 * User: a1
 * Date: 2018/3/7
 * Time: 下午4:41
 */
class ImportAction extends CommonAction{

    private $year;

    private $tmInfo;

    private $csv_dir = "/home/www/dunmama-data";

    //日志
    private $fp = null;

    //初始化
    protected function _initialize(){
        $this->year = $_GET['dunmamaYear'];
        $this->tmInfo = $_GET['dunmamaTmInfo'];
        if(empty($this->year) || empty($this->tmInfo)){
            echo "need year or tmInfo";
            exit;
        }
        $this->fp = @fopen( $this->csv_dir . "/import-error.log","a+");
    }

    //记录日志
    private function _log_record($data = []){
        @fwrite($this->fp, json_encode($data));
    }

    //导入《商标注册人信息》
    public function trademarkRegisterInfo(){
        $filename = "商标注册人信息.csv";
        $year = $this->year;
        $tmInfo = $this->tmInfo;
        $filePath = sprintf("%s/%s/tmInfo_%s/%s", $this->csv_dir, $year, $tmInfo, $filename);
        $result = $this->readCvs($filePath);
        $i = 0;
        foreach ($result as $key => $value) {
            //跳过表头
            if( $i > 0 ){
                //过滤不合规的数据
                if( count($value) == 6 ){
                    //数组元素整体去掉前后空格，保留中间空格
                    $value = array_map(function ($val){ return trim($val);},$value);
                    //商标编号
                    $trademark_sn = $value[0];
                    //商标分类
                    $international_cate = $value[1];
                    //注册人中文名称
                    $register_chinese_name = $value[2];
                    //注册人英文名称
                    $register_foreign_name = $value[3];
                    //注册人中文地址
                    $register_chinese_address = $value[4];
                    //注册人英文地址
                    $register_foreign_address = $value[5];
                    // 查询数据，如果存在则不进行插入
                    $filter = [
                        'trademark_sn' => $trademark_sn,
                        "international_cate" => $international_cate,
                    ];
                    //$query = new MongoDB\Driver\Query($filter);
                    //$cursor = $this->mongo->executeQuery('dunmama.trademark_register_info', $query)->toArray();
                    //if( $cursor == null || count($cursor) == 0 ){
                        $bulk = new MongoDB\Driver\BulkWrite;
                        //组织文档
                        $document = [
                            '_id' => new MongoDB\BSON\ObjectID,
                            'year' => $year,
                            'tmInfo' => $tmInfo,
                            'trademark_sn' => $trademark_sn,
                            'international_cate' => $international_cate,
                            'register_chinese_name' => $register_chinese_name,
                            'register_foreign_name' => $register_foreign_name,
                            'register_chinese_address' => $register_chinese_address,
                            'register_foreign_address' => $register_foreign_address,
                        ];
                        $bulk->insert($document);
                        $this->mongo->executeBulkWrite('dunmama.trademark_register_info', $bulk);
                    //}
                }
            }
            $i++;
        }
        echo "数据导入成功" . PHP_EOL;
    }

    //导入《注册商标基本信息》
    public function trademarkBaseInfo(){
        $filename = "注册商标基本信息.csv";
        $year = $this->year;
        $tmInfo = $this->tmInfo;
        $filePath = sprintf("%s/%s/tmInfo_%s/%s", $this->csv_dir, $year, $tmInfo, $filename);
        $result = $this->readCvs($filePath);
        $i = 0;
        foreach ($result as $key => $value) {
            //跳过表头
            if( $i > 0 ){;
                //过滤不合规的数据
                if( count($value) == 22 ) {
                    //数组元素整体去掉前后空格，保留中间空格
                    $value = array_map(function ($val) {
                        return trim($val);
                    }, $value);
                    //商标编号
                    $trademark_sn = $value[0];
                    //商标分类
                    $international_cate = $value[1];
                    //申请日期
                    $apply_time = $value[2];
                    //商标名称
                    $trademark_name = $value[3];
                    //商标类型
                    $trademark_type = $value[4];
                    //代理机构代码
                    $agency_sn = $value[5];
                    //初审公告期号
                    $first_trial_notice_issue_sn = $value[6];
                    //初审公告日期
                    $first_trial_notice_time = $value[7];
                    //注册公告期号
                    $registered_notice_issue_sn = $value[8];
                    //注册公告日期
                    $registered_notice_time = $value[9];
                    //专用期开始日期
                    $exclusive_start_time = $value[10];
                    //专用期结束日期
                    $exclusive_end_time = $value[11];
                    //专用有效期
                    $exclusive_vaild_date = $value[12];
                    //商标设计说明
                    $design_desc = $value[13];
                    //商标颜色说明
                    $color_desc = $value[14];
                    //放弃专用权说明
                    $give_up_exclusive_desc = $value[15];
                    //是否立体商标
                    $stereo_status = $value[16];
                    //是否共有申请
                    $coowner_apply_status = $value[17];
                    //商标形态
                    $trademark_style = $value[18];
                    //地理标志信息
                    $geographical = $value[19];
                    //颜色标志
                    $color_indication = $value[20];
                    //是否驰名商标
                    $reputed_status = $value[21];
                    // 查询数据，如果存在则不进行插入
                    $filter = [
                        'trademark_sn' => $trademark_sn,
                        "international_cate" => $international_cate,
                    ];
                    //$query = new MongoDB\Driver\Query($filter);
                    //$cursor = $this->mongo->executeQuery('dunmama.trademark_base_info', $query)->toArray();
                    //if ($cursor == null || count($cursor) == 0) {
                        $bulk = new MongoDB\Driver\BulkWrite;
                        //组织文档
                        $document = [
                            '_id' => new MongoDB\BSON\ObjectID,
                            'year' => $year,
                            'tmInfo' => $tmInfo,
                            'trademark_sn' => $trademark_sn,
                            'international_cate' => $international_cate,
                            'apply_time' => $apply_time,
                            'trademark_name' => $trademark_name,
                            'trademark_type' => $trademark_type,
                            'agency_sn' => $agency_sn,
                            'first_trial_notice_issue_sn' => $first_trial_notice_issue_sn,
                            'first_trial_notice_time' => $first_trial_notice_time,
                            'registered_notice_issue_sn' => $registered_notice_issue_sn,
                            'registered_notice_time' => $registered_notice_time,
                            'exclusive_start_time' => $exclusive_start_time,
                            'exclusive_end_time' => $exclusive_end_time,
                            'exclusive_vaild_date' => $exclusive_vaild_date,
                            'design_desc' => $design_desc,
                            'color_desc' => $color_desc,
                            'give_up_exclusive_desc' => $give_up_exclusive_desc,
                            'stereo_status' => $stereo_status,
                            'coowner_apply_status' => $coowner_apply_status,
                            'trademark_style' => $trademark_style,
                            'geographical' => $geographical,
                            'color_indication' => $color_indication,
                            'reputed_status' => $reputed_status,
                        ];
                        try{
                            $bulk->insert($document);
                            $this->mongo->executeBulkWrite('dunmama.trademark_base_info', $bulk);
                        } catch (Exception $e) {
                            $this->_log_record(['error'=>$e->getMessage()]);
                            $this->_log_record($document);
                        }
                    //}
                }
            }
            $i++;
        }
        echo "数据导入成功" . PHP_EOL;
    }

    //导入《注册商标商品服务信息》
    public function trademarkGoodsServiceInfo(){
        $filename = "注册商标商品服务信息.csv";
        $year = $this->year;
        $tmInfo = $this->tmInfo;
        $filePath = sprintf("%s/%s/tmInfo_%s/%s", $this->csv_dir, $year, $tmInfo, $filename);
        $result = $this->readCvs($filePath);
        $i = 0;
        foreach ($result as $key => $value){
            //跳过表头
            if( $i > 0 ) {
                //过滤不合规的数据
                if (count($value) == 6) {
                    //数组元素整体去掉前后空格，保留中间空格
                    $value = array_map(function ($val) {
                        return trim($val);
                    }, $value);
                    //商标编号
                    $trademark_sn = $value[0];
                    //商标分类
                    $international_cate = $value[1];
                    //群组编号
                    $group_sn = $value[2];
                    //商品编号
                    $goods_sn = $value[3];
                    //商品中文名称
                    $goods_chinese_name = $value[4];
                    //商品状态
                    $goods_status = $value[5];
                    // 查询数据，如果存在则不进行插入
                    $filter = [
                        'trademark_sn' => $trademark_sn,
                        "international_cate" => $international_cate,
                        'group_sn' => $group_sn,
                        'goods_sn' => $goods_sn
                    ];
                    //$query = new MongoDB\Driver\Query($filter);
                    //$cursor = $this->mongo->executeQuery('dunmama.trademark_goods_service_info', $query)->toArray();
                    //if ($cursor == null || count($cursor) == 0) {
                        $bulk = new MongoDB\Driver\BulkWrite;
                        //组织文档
                        $document = [
                            '_id' => new MongoDB\BSON\ObjectID,
                            'year' => $year,
                            'tmInfo' => $tmInfo,
                            'trademark_sn' => $trademark_sn,
                            'international_cate' => $international_cate,
                            'group_sn' => $group_sn,
                            'goods_sn' => $goods_sn,
                            'goods_chinese_name' => $goods_chinese_name,
                            'goods_status' => $goods_status,
                        ];
                        try{
                            $bulk->insert($document);
                            $this->mongo->executeBulkWrite('dunmama.trademark_goods_service_info', $bulk);
                        } catch (Exception $e) {
                            $this->_log_record(['error'=>$e->getMessage()]);
                            $this->_log_record($document);
                        }
                    //}
                }
            }
            $i++;
        }
        echo "数据导入成功" . PHP_EOL;
    }
    //导入《注册商标优先权信息》

    //导入《注册商标共有人信息》
    public function trademarkCoownerInfo(){
        $filename = "注册商标共有人信息.csv";
        $year = $this->year;
        $tmInfo = $this->tmInfo;
        $filePath = sprintf("%s/%s/tmInfo_%s/%s", $this->csv_dir, $year, $tmInfo, $filename);
        $result = $this->readCvs($filePath);
        $i = 0;
        foreach ($result as $key => $value){
            //跳过表头
            if( $i > 0 ) {
                //过滤不合规的数据
                if (count($value) == 5) {
                    //数组元素整体去掉前后空格，保留中间空格
                    $value = array_map(function ($val) {
                        return trim($val);
                    }, $value);
                    //商标编号
                    $trademark_sn = $value[0];
                    //共有人中文名称
                    $coowner_chinese_name = $value[1];
                    //共有人英文名称
                    $coowner_foreign_name = $value[2];
                    //共有人中文地址
                    $coowner_chinese_address = $value[3];
                    //共有人英文地址
                    $coowner_foreign_address = $value[4];
                    // 查询数据，如果存在则不进行插入
                    $filter = [
                        'trademark_sn' => $trademark_sn,
                        "coowner_chinese_name" => $coowner_chinese_name,
                    ];
                    //$query = new MongoDB\Driver\Query($filter);
                    //$cursor = $this->mongo->executeQuery('dunmama.trademark_coowner_info', $query)->toArray();
                    //if ($cursor == null || count($cursor) == 0) {
                        $bulk = new MongoDB\Driver\BulkWrite;
                        //组织文档
                        $document = [
                            '_id' => new MongoDB\BSON\ObjectID,
                            'year' => $year,
                            'tmInfo' => $tmInfo,
                            'trademark_sn' => $trademark_sn,
                            'coowner_chinese_name' => $coowner_chinese_name,
                            'coowner_foreign_name' => $coowner_foreign_name,
                            'coowner_chinese_address' => $coowner_chinese_address,
                            'coowner_foreign_address' => $coowner_foreign_address,
                        ];
                        $bulk->insert($document);
                        $this->mongo->executeBulkWrite('dunmama.trademark_coowner_info', $bulk);
                    //}
                }
            }
            $i++;
        }
        echo "数据导入成功" . PHP_EOL;
    }

    //导入《国际注册基本信息》
    public function trademarkInternationalRegisteredBaseInfo(){
        try{
            $filename = "国际注册基本信息.csv";
            $year = $this->year;
            $tmInfo = $this->tmInfo;
            $filePath = sprintf("%s/%s/tmInfo_%s/%s", $this->csv_dir, $year, $tmInfo, $filename);
            $result = $this->readCvs($filePath);
            $i = 0;
            //redis缓存
            $this->redis_cache_connect();
            $cacheKey = "trademark_international_registered_base_info_".$year."_tmInfo_".$tmInfo;
            foreach ($result as $key => $value){
                //跳过表头
                if( $i > 0 ) {
                    //过滤不合规的数据
                    if (count($value) == 10) {
                        //数组元素整体去掉前后空格，保留中间空格
                        $value = array_map(function ($val) {
                            return trim($val);
                        }, $value);
                        //商标编号
                        $trademark_sn = $value[0];
                        $international_registered_sn = $value[1];
                        $international_registered_time = $value[2];
                        $international_notify_time = $value[3];
                        $international_apply_language = $value[4];
                        $international_apply_type = $value[5];
                        $international_notice_issue_sn = $value[6];
                        $international_notice_time = $value[7];
                        $after_designated_time = $value[8];
                        $base_registered_time = $value[9];
                        //如果已经添加过，则直接跳出
                        if ($this->redis_cache->sismember($cacheKey, $trademark_sn)) {
                            continue;
                        }
                        // 查询数据，如果存在则不进行插入
                        $filter = [
                            'trademark_sn' => $trademark_sn,
                        ];
                        //$query = new MongoDB\Driver\Query($filter);
                        //$cursor = $this->mongo->executeQuery('dunmama.trademark_international_registered_base_info', $query)->toArray();
                        //if ($cursor == null || count($cursor) == 0) {
                            $bulk = new MongoDB\Driver\BulkWrite;
                            //组织文档
                            $document = [
                                '_id' => new MongoDB\BSON\ObjectID,
                                'year' => $year,
                                'tmInfo' => $tmInfo,
                                'trademark_sn' => $trademark_sn,
                                'international_registered_sn' => $international_registered_sn,
                                'international_registered_time' => $international_registered_time,
                                'international_notify_time' => $international_notify_time,
                                'international_apply_language' => $international_apply_language,
                                'international_apply_type' => $international_apply_type,
                                'international_notice_issue_sn' => $international_notice_issue_sn,
                                'international_notice_time' => $international_notice_time,
                                'after_designated_time' => $after_designated_time,
                                'base_registered_time' => $base_registered_time,
                            ];
                            $bulk->insert($document);
                            $this->mongo->executeBulkWrite('dunmama.trademark_international_registered_base_info', $bulk);
                            $this->redis_cache->sadd($cacheKey, $trademark_sn);
                        //}
                    }
                }
                $i++;
            }
            echo "数据导入成功" . PHP_EOL;
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }

    private function readCvs($filePath){
        if (file_exists($filePath)) {
            # code...
            $handle = fopen($filePath, 'rb');
            while (feof($handle)===false) {
                # code...
                yield fgetcsv($handle);
            }
            fclose($handle);
        } else {
            echo "file not exists !!! {$filePath}" . PHP_EOL;
        }
    }

    //@brief 导入最新公告
    public function exportThread()
    {
	  exit;
        $newses = M('news')->where(array('cat_id' => 1, 'isPass' => 1))->select();
        foreach ($newses as $news){
            $thread = array(
                'author' => $news['author'],
                'channelid' => '79',
                'title' => $news['title'],
                'description' => $news['summary'],
                'source' => $news['source'],
                'thumbnail' => '/' . $news['logo'],
                'views' => $news['viewCount'],
                'replys' => 0,
                'addtime' => $news['add_time']
            );


            $threadId = M('cms_thread')->add($thread);
            echo M()->getError();
            echo M()->getDbError();

            $post = array(
                'threadid'    =>  $threadId,
                'seotitle'    =>  $news['description'],
                'keywords'    =>  $news['keywords'],
                'content'    =>  $news['content'],
            );
            M('cms_post')->add($post);

            echo M()->getError();
            echo M()->getDbError();
            $tags = explode(" ", $news['keywords']);


            //修复tag关系
            foreach ($tags as $name) {
                if ( empty($name)) continue;
                $tag = D('CmsTag')->where(array('name' => $name))->find();
                if (!$tag) {
                    $ret = D('CmsTag')->add(array('name' => $name));
                    $tag['id'] = $ret;
                }
                D('CmsThreadTag')->add(array('threadid' => $threadId, 'tagid' => $tag['id']));
            }
        }
        echo '资讯数据导入成功';
    }

    public function __destruct()
    {
        parent::__destruct();
        @fclose($this->fp);
    }
}
